/**
 * @projectName base-yl
 * @package com.base.yl.cloudwechat.config.handler
 * @className com.base.yl.cloudwechat.config.handler.ResponseBodyHandler
 */
package com.answer.wx.gateway.config.handler;

import com.alibaba.fastjson.JSON;
import com.answer.wx.common.aop.ApiOptions;
import com.answer.wx.common.response.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * ResponseBodyHandler
 * @description 返回对象组装
 * @author answer_wx
 * @date 2022/8/4 18:51
 * @version 1.0
 */
@RestControllerAdvice
@Slf4j
public class ResponseBodyHandler implements ResponseBodyAdvice {
    private final static Map<Object, Object> EMPTY_BODY = new HashMap<>(1);

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {

        Method method = methodParameter.getMethod();
        assert method != null;
        ApiOptions annotation = method.getAnnotation(ApiOptions.class);
        if (annotation != null) {
            return annotation.format();
        }
        return false;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (body == null) {
            body = EMPTY_BODY;
        }
        ApiResponse response = ApiResponse.ok(body);
        String data = JSON.toJSONString(response);
        log.info(String.format("ApiResponse %s", data));

        return response;
    }
}